import 'dart:ffi';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:media_kit/media_kit.dart';
import 'package:media_kit_video/media_kit_video.dart';
import 'package:yuwei_study_language_tools_flutter/panel/right_panel.dart';
import 'package:yuwei_study_language_tools_flutter/tools/subtitle_tools.dart';

import '../pojo/srtspan.dart';
import '../widget/number_input_widget.dart';
import '../widget/subtitle_widget.dart';

class StudyScreen extends StatefulWidget {
  StudyScreen(
      {super.key,
      required this.mode,
      this.mp4Path,
      this.srtPath1,
      this.srtPath2});

  // 运行模式
  int mode = 0;

  // mp4路径
  String? mp4Path;

  // srt路径
  String? srtPath1;
  String? srtPath2;

  @override
  State<StudyScreen> createState() => _StudyScreenState();
}

class _StudyScreenState extends State<StudyScreen> {
  late final player = Player();
  late final videoController = VideoController(player);

  String curSubtitle1 = "test";
  String curSubtitle2 = "测试";

  bool showSubtitle1 = true;
  bool showSubtitle2 = false;

  // 跳转字幕索引
  int savedIndex = -1;

  // 播放开关
  bool playOn = true;

  // 等待秒数
  int repeatWaitTime = 3;

  // 重复次数
  int repeatQty = 3;

  // 输入的句子
  String inputSubtitle = "";
  List<String> inputWords = [];
  List<String> curSubtitleWords = [];

  // 字幕列表
  List<SrtSpan>? srts;

  // 最后字幕索引
  int lastFindIndex = -1;

  // 当前字幕索引
  int curIndex = -1;

  // 最近输入的内容
  String inputLine = "";

  // 正在输入的文字
  String inputWord = "";

  // 进度ok信息
  Map<int, bool> srtsOkMap = {};

  // 键盘监听
  FocusNode focusNode = FocusNode();

  // 是否显示右侧
  var _showRightPanel = true;

  @override
  void initState() {
    super.initState();

    // 播放视频
    playMp4();

    // 打开srt
    openSrt();

    // 监听视频播放状态
    player.stream.position.listen((Duration position) {
      // 刷新字幕
      findSubtitles(position.inMilliseconds);

      // 一个字幕快结束时停止
      if (curIndex != -1) {
        SrtSpan ss = srts![curIndex];
        if (srtsOkMap[curIndex] == null &&
            (position.inMilliseconds - ss.endTime).abs() < 100) {
          player.pause();
          savedIndex = curIndex;
          repeatOrConinue();
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    FocusScope.of(context).requestFocus(focusNode);
    FocusScope.of(context).autofocus(focusNode);

    return Row(
      children: [
        Expanded(
          child: Column(
            children: [
              // 播放器
              buildMoviePanel(),
              // 字幕栏
              buildSubtitlePanel(),
              // 工具栏
              buildToolBar(),
              // 学习进度
              buildProgressBar(),
              // 输入栏
              buildInputPanel()
            ],
          ),
        ),
        _showRightPanel
            ? RightPanel()
            : Container(
                width: 10,
              )
      ],
    );
  }

  // 创建播放器模块
  buildMoviePanel() {
    return Expanded(
        child: Video(
      controller: videoController,
      subtitleViewConfiguration: SubtitleViewConfiguration(visible: false),
    ));
  }

  // 创建字幕
  buildSubtitlePanel() {
    List<Widget> l = [];
    if (showSubtitle1! && widget.srtPath1 != null) {
      l.add(SubtitleWidget(
        height: 50,
        fontSize: 25,
        showSubtitle: showSubtitle1,
        subtitle: curSubtitle1,
        textColor: Colors.white,
        wrongTextColor: Colors.white,
        backgroundColor: Colors.black,
      ));
    }
    if (showSubtitle2! && widget.srtPath2 != null) {
      l.add(SubtitleWidget(
        height: 50,
        fontSize: 25,
        showSubtitle: showSubtitle2,
        subtitle: curSubtitle2,
        textColor: Colors.white,
        wrongTextColor: Colors.white,
        backgroundColor: Colors.black,
      ));
    }
    return Column(
      children: l,
    );
  }

  // 工具栏
  buildToolBar() {
    return Container(
      height: 40,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          TextButton(
              onPressed: () {
                op("open");
              },
              child: Text("打开并播放视频")),
          TextButton(
              onPressed: () {
                op("play_or_pause");
              },
              child: Text("播放或暂停")),
          TextButton(
              onPressed: () {
                op("switch_sub1");
              },
              child: Text("字幕1")),
          TextButton(
              onPressed: () {
                op("switch_sub2");
              },
              child: Text("字幕2")),
          TextButton(
              onPressed: () {
                op("prev_srt");
              },
              child: Text("上一句")),
          TextButton(
              onPressed: () {
                op("next_srt");
              },
              child: Text("下一句")),
          Text(srts == null
              ? ""
              : "已完成:${srtsOkMap.keys.length}/${srts!.length}"),
          SizedBox(
            width: 20,
          ),
          Text("等待:"),
          Material(
              child: NumberInputWidget(
            onValueChanged: repeatWaitTimeChange,
            num: 3,
          )),
          Text("秒"),
          SizedBox(
            width: 20,
          ),
          TextButton(
              onPressed: () {
                print("显示右侧栏目");
                op("show_right_panel");
              },
              child: Text("显右"))
        ],
      ),
    );
  }

  buildInputPanel() {
    return Container(
      height: 150,
      child: Column(
        children: [
          SubtitleWidget(
            height: 50,
            fontSize: 25,
            showSubtitle: true,
            subtitle: curSubtitle1,
            textColor: Colors.white,
            inputWords: inputWords,
            // 和背景色一样
            wrongTextColor: Colors.deepPurpleAccent,
            backgroundColor: Colors.deepPurpleAccent,
            undLineColor: Colors.white,
            showUnderLine: true,
          ),
          Container(
            decoration: BoxDecoration(color: Colors.lightBlueAccent),
            width: double.infinity,
            alignment: Alignment.center,
            height: 50,
            child: Text(
              inputLine,
              style: TextStyle(
                  fontSize: 36,
                  color: Colors.white,
                  decoration: TextDecoration.none),
            ),
          ),
          KeyboardListener(
            focusNode: focusNode,
            autofocus: true, // 要开启自动焦点
            onKeyEvent: (KeyEvent event) {
              if (event.runtimeType == KeyDownEvent) {
                print(event.character);
                print(event.logicalKey.keyLabel);
                print(event.physicalKey.debugName);
                if (event.logicalKey.keyLabel == "Enter" ||
                    event.physicalKey.debugName == "Space") {
                  setState(() {
                    inputLine = inputWord;
                    inputWord = "";
                    checkInputSubtitle();
                  });
                } else if (event.logicalKey.keyLabel == "Backspace") {
                  if (inputWord.length > 0) {
                    setState(() {
                      print(inputWord);
                      if (inputWord.length == 1) {
                        inputWord = "";
                      } else {
                        inputWord =
                            inputWord.substring(0, inputWord.length - 2);
                      }
                      print(inputWord);
                    });
                  }
                } else if (event.character != null) {
                  setState(() {
                    inputWord += event.character!;
                  });
                }
              }
            },
            child: Container(
              decoration: BoxDecoration(color: Colors.green),
              width: double.infinity,
              alignment: Alignment.center,
              height: 50,
              child: Text(
                inputWord,
                style: TextStyle(
                    fontSize: 36,
                    color: Colors.white,
                    decoration: TextDecoration.none),
              ),
            ),
          ),
        ],
      ),
    );
  }

  buildProgressBar() {
    return Container(
      width: double.infinity,
      height: 20,
      decoration: BoxDecoration(color: Colors.grey),
      child: Flex(
        direction: Axis.horizontal,
        children: buildProgressBarDivs(),
      ),
    );
  }

  buildProgressBarDivs() {
    List<Widget> list = [];
    if (srts == null) {
      Widget w = Expanded(
        flex: 1,
        child: Container(
          height: 28.0,
          color: Colors.white10,
        ),
      );
      list.add(w);
    } else {
      for (int i = 0; i < srts!.length; i++) {
        Widget w = Expanded(
          flex: 1,
          child: GestureDetector(
            onTap: () {
              // jumpTo(i);
            },
            child: Container(
              height: 28.0,
              color: srtsOkMap[i] == null ? Colors.grey : Colors.green,
              margin: EdgeInsets.all(2),
              alignment: Alignment.center,
              child: Container(
                  alignment: Alignment.center,
                  width: 20,
                  color: curIndex == i
                      ? Colors.red
                      : (srtsOkMap[i] == null ? Colors.grey : Colors.green),
                  child: Text(
                    "${i + 1}",
                    style: TextStyle(color: Colors.white),
                  )),
            ),
          ),
        );
        list.add(w);
      }
    }
    return list;
  }

  // 操作汇总
  void op(String op) {
    print("执行${op}");

    switch (op) {
      case "open":
        print("打开并播放");
        String url = "/Users/qiang/英语/译林英语/unit1/unit1storytime.mp4";
        player.open(Media(url));
        break;
      case "play_or_pause":
        print("播放或暂停");
        // player.playOrPause();
        playOn = !playOn;
        if (playOn) {
          player.play();
        } else {
          player.pause();
        }
        setState(() {});
        break;
      case "switch_sub1":
        setState(() {
          showSubtitle1 = !showSubtitle1;
        });

        break;
      case "switch_sub2":
        setState(() {
          showSubtitle2 = !showSubtitle2;
        });
        break;
      case "prev_srt":
        prevSrt();
        break;
      case "next_srt":
        nextSrt();
        break;
      case "show_right_panel":
        print("切换显示右侧栏目${_showRightPanel}");
        setState(() {
          _showRightPanel = !_showRightPanel;
        });

        break;
    }
  }

  void playMp4() {
    print("播放器视频:");
    print(widget.mp4Path!);
    player.open(Media(widget.mp4Path!));
  }

  Future<void> openSrt() async {
    // File file = File("/Users/qiang/Downloads/unity2story.srt");
    File file = File(widget.srtPath1!);
    String content = await file.readAsString();
    print("读取到内容:" + content);
    // srts = SubtitleTools.handleSrtContent(content);
    srts = SubtitleTools.handleSrtContent(content);
  }

  // 查找当前字幕
  void findSubtitles(int curTime) {
    // 1. 字幕还没加载完成,直接退出
    if (srts == null) return;

    int tmpIndex = -1;
    String tmpSubTitle = "";
    // int startFind = srts!.length;

    // 还没加载过任何字幕，从头开始找
    int startFind = 0;

    // 加载过，先判断是否在之前范围内
    if (lastFindIndex != -1) {
      SrtSpan ss = srts![lastFindIndex];
      if (ss.startTime <= curTime) {
        if (ss.endTime >= curTime) {
          // tmpIndex = lastFindIndex;
          // tmpSubTitle = ss.content;
          startFind = lastFindIndex;
        } else {
          // 往后找
          startFind = curIndex + 1;
        }
      } else {
        // 从头找
        startFind = 0;
      }
    }

    for (int i = startFind; i < srts!.length; i++) {
      SrtSpan ss = srts![i];
      if (ss.startTime <= curTime) {
        if (ss.endTime >= curTime) {
          // 在范围内
          tmpIndex = i;
          tmpSubTitle = ss.content;
          lastFindIndex = i;
          break;
        }
      } else {
        // 结束查找
        break;
      }
    }
    // print("${tmpIndex}:${tmpSubTitle}");
    if (curIndex != tmpIndex) {
      setState(() {
        curIndex = tmpIndex;
        curSubtitle1 = tmpSubTitle;
        print(tmpSubTitle);
        refreshCurSubtitleWords();
      });
    }
    // print("当前字幕:${curIndex},${curSubtitle1}");
  }

  bool jumpBack = true;

  Future<void> repeatOrConinue() async {
    print("隔${repeatWaitTime}秒跳转");
    jumpBack = true;
    Future.delayed(Duration(milliseconds: repeatWaitTime * 1000), () {
      // 如果已完成，则继续播放，如果未完成，则跳回
      if (jumpBack && playOn) {
        if (srtsOkMap[savedIndex] == null) {
          SrtSpan srt = srts![savedIndex];
          player.seek(Duration(milliseconds: srt.startTime));
        }
        player.play();
      }
    });
  }

  void prevSrt() {
    if (srts == null) return;
    jumpBack = false;
    print("curIndex = ${curIndex}");
    int jumpIndex = -1;
    if (curIndex != -1) {
      jumpIndex = curIndex - 1;
    } else {
      jumpIndex = lastFindIndex;
    }
    if (jumpIndex != -1) {
      player.seek(Duration(milliseconds: srts![jumpIndex].startTime));
      player.play();
    }
  }

  void nextSrt() {
    if (srts == null) return;
    jumpBack = false;
    print("curIndex = ${curIndex}");
    int jumpIndex = -1;
    if (curIndex != -1) {
      jumpIndex = curIndex + 1;
    } else {
      jumpIndex = lastFindIndex + 1;
    }
    if (jumpIndex != srts!.length) {
      player.seek(Duration(milliseconds: srts![jumpIndex].startTime));
      player.play();
    }
  }

  void repeatWaitTimeChange(int t) {
    print("数字改变:${t}");
    this.repeatWaitTime = t;
  }

  // 检测输入内容是否正确
  void checkInputSubtitle() {
    // 比较当前输入的inputLine
    // 和当前的完整字幕curSubtitle1
    // 如果符合 则放入inputWords
    if (curSubtitleWords.contains(inputLine)) {
      inputWords.add(inputLine);
      print("符合,放入！");

      List<bool> checkList = [];
      int k = 0;
      for (int i = 0; i < curSubtitleWords.length; i++) {
        checkList.add(false);
        for (int j = k; j < inputWords.length; j++) {
          if (curSubtitleWords[i].toLowerCase() == inputWords[j]) {
            checkList[i] = true;
            k = j;
            break;
          }
        }
      }
      bool ok = true;
      for (int i = 0; i < curSubtitleWords.length; i++) {
        if (checkList[i] == false) {
          ok = false;
        }
      }
      if (ok) {
        srtsOkMap[curIndex] = true;
      }
    }
  }

  void refreshCurSubtitleWords() {
    curSubtitleWords = SubtitleTools.strToWords(curSubtitle1);
    inputWords = [];
    print(curSubtitleWords);
  }
}
